import {findNodeHandle} from 'react-native'

const LocationUtil = {}

function MeasureOnSuccessCallback(msc, cb) {
  if (typeof msc !== 'object') {
    return
  }
  if (isNaN(msc.x)) {
    return
  }
  const x = Math.ceil(msc.x)
  const y = Math.ceil(msc.y)
  const width = Math.ceil(msc.width)
  const height = Math.ceil(msc.height)
  const pageX = Math.ceil(msc.pageX)
  const pageY = Math.ceil(msc.pageY)
  cb && cb({x, y, width, height, pageX, pageY})
}

LocationUtil.relativeLocation = (ref, callBack = () => {}) => {
  const handle = findNodeHandle(ref)
  if (!handle) return
  if (!ref) return
  if (!ref.measure) return
  ref.measure(msc => {
    MeasureOnSuccessCallback(msc, callBack)
  })
}

LocationUtil.absoluteWindowsLoc = (ref, callBack = () => {}) => {
  const handle = findNodeHandle(ref)
  if (!handle) return
  if (!ref) return
  if (!ref.measureInWindow) return
  ref.measureInWindow(msc => {
    MeasureOnSuccessCallback(msc, callBack)
  })
}

export default LocationUtil
